#include "dbusvfsinterface.h"
#include "mainwindow.h"

DbusVfsInterface::DbusVfsInterface(QObject *parent) : QObject(parent)
{
    FileInfo::registerMetaType();
    FileInfoList::registerMetaType();
    connect(MainWindow::getInstance(), &MainWindow::sigConnected, this, &DbusVfsInterface::sigDeviceUpdate);
    connect(MainWindow::getInstance(), &MainWindow::sigDisconnect, this, [=]() {
        Q_EMIT sigDeviceUpdate(QString(""));
    });
    connect(MainWindow::getInstance(), &MainWindow::sigFileInfoList, this, [=](const QMap<QString, FileInfo> &fileMap) {
        qInfo() << "Publish file list.";
        m_fileMap.clear();
        m_fileMap = fileMap;
        FileInfoList list;
        QMap<QString, FileInfo>::const_iterator it = fileMap.begin();
        while (it != fileMap.end()) {
            list.addFileInfo(it.value());
            it++;
        }
        Q_EMIT sigFileInfoList(list);
    });
}

QString DbusVfsInterface::getDeviceName()
{
    qInfo() << "Get current external connection request name.";
    return MainWindow::getInstance()->getDeviceName();
}

QString DbusVfsInterface::getMountDir()
{
    qInfo() << "External request to get the current mount directory.";
    return MOUNT_DIR;
}

void DbusVfsInterface::getFileInfoList(QString path)
{
    qInfo() << "External request for file list." << path;
    MainWindow::getInstance()->list(path);
}

void DbusVfsInterface::downFile(QStringList fromPathList, QString targetPath)
{
    qInfo() << "External request for download file." << targetPath;
    QList<FileInfo> list;
    for (int i = 0; i < fromPathList.size(); i++) {
        list.append(m_fileMap.find(fromPathList.value(i)).value());
    }
    MainWindow::getInstance()->downFile(list, targetPath);
}
